package org.shiro.demo.controller;

import java.util.Date;

import javax.annotation.Resource;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.apache.shiro.subject.Subject;
import org.shiro.demo.dao.util.Pagination;
import org.shiro.demo.dao.util.UserUtils;
import org.shiro.demo.disruptor.DisruptorUtils;
import org.shiro.demo.disruptor.TradeTransaction;
import org.shiro.demo.disruptor.TradeTransactionEventTranslator;
import org.shiro.demo.entity.Administrator;
import org.shiro.demo.entity.ResponseResult;
import org.shiro.demo.entity.User;
import org.shiro.demo.entity.WeixinOpen;
import org.shiro.demo.service.IAdminService;
import org.shiro.demo.service.IBaseService;
import org.shiro.demo.service.IUserService;
import org.shiro.demo.service.realm.ShiroDbRealm;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping(value = "/user")
public class UserController {

	@Resource(name = "userService")
	private IUserService userService;

	@Resource(name = "adminService")
	private IAdminService adminService;
	@Resource(name = "baseService")
	private IBaseService baseService;

	@RequestMapping(value = "/findUsers")
	@ResponseBody
	@RequiresAuthentication
	@RequiresRoles("super-administrator")
	public Pagination<User> findUsers(@RequestParam("pageSize") Integer pageSize, //
			@RequestParam("pageNumber") Integer pageNumber,//
			@RequestParam("orderBy") String orderBy,//
			@RequestParam("asc") Boolean asc) {

		// List<QueryCondition> queryConditions = new
		// ArrayList<QueryCondition>();
		Pagination<User> pagination = null;
		if (orderBy != null && asc != null) {
			pagination = userService.getPagination(User.class, null, " order by o." + orderBy + " " + (asc ? " ASC " : " DESC "), pageNumber, pageSize);
		} else {
			pagination = userService.getPagination(User.class, null, null, pageNumber, pageSize);
		}
		return pagination;
	}

	@RequestMapping(value = "/findWusers")
	@ResponseBody
	@RequiresAuthentication
	@RequiresRoles("super-administrator")
	public Pagination<WeixinOpen> findWUsers(@RequestParam("pageSize") Integer pageSize, //
			@RequestParam("pageNumber") Integer pageNumber,//
			@RequestParam("orderBy") String orderBy,//
			@RequestParam("asc") Boolean asc) {

		// List<QueryCondition> queryConditions = new
		// ArrayList<QueryCondition>();
		Pagination<WeixinOpen> pagination = null;
		if (orderBy != null && asc != null) {
			pagination = baseService.getPagination(WeixinOpen.class, null, " order by o.bindTime" + " " + (asc ? " ASC " : " DESC "), pageNumber, pageSize);
		} else {
			pagination = baseService.getPagination(WeixinOpen.class, null, null, pageNumber, pageSize);
		}
		return pagination;
	}

	/**
	 * 测试
	 * 
	 * @param user
	 * @return
	 */
	// @RequestMapping(value = "/test")
	// @ResponseBody
	// public Object test() {
	// DisruptorUtils.publish(new TradeTransactionEventTranslator(new
	// TradeTransaction("hi", new Date(), "1", 12.78)));
	// return 1;
	// }

	/**
	 * 查看个人资料
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/look")
	@ResponseBody
	@RequiresAuthentication
	public Object look() {
		ResponseResult rr = new ResponseResult();
		// User user = UserUtils.getCurrentUser();
		// User dbuser = userService.getByAccount(user.getAccount());
		// if (null != dbuser) {
		// return dbuser;
		// }
		// u.setRoles(null);
		Object object = SecurityUtils.getSubject().getPrincipal();

		if (object instanceof Administrator) {
			Administrator admin = adminService.getByPhone(((Administrator) object).getPhone());
			admin.setPassword("");
			rr.setObject(admin);
		} else {
			User customer = userService.getByPhone(((User) object).getPhone());
			customer.setPassword("");
			// customer.setSmsCode("");
			rr.setObject(customer);
		}

		rr.setCode(1);
		return rr;

	}

	/**
	 * 查看个人资料
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/verify")
	@ResponseBody
	@RequiresAuthentication
	public Object verify() {
		ResponseResult rr = new ResponseResult();
		rr.setCode(1);
		return rr;

	}

	/**
	 * 查看个人资料
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/logout")
	@ResponseBody
	@RequiresAuthentication
	public Object logout() {
		ResponseResult rr = new ResponseResult();
		try {
			Subject currentUser = SecurityUtils.getSubject();
			currentUser.logout();
		} catch (Exception e) {
			rr.setCode(0);
			return rr;
		}
		rr.setCode(1);
		return rr;

	}

	/**
	 * 查看个人资料
	 * 
	 * @param user2
	 * @return
	 */
	@RequestMapping(value = "/modify", method = RequestMethod.POST)
	@ResponseBody
	@RequiresAuthentication
	@RequiresRoles("customer")
	public ResponseResult modify(User modifyUser) {
		try {
			User user = (User) SecurityUtils.getSubject().getPrincipal();

			User userInDB = userService.getByPhone(user.getPhone());
			// userInDB.setAddress(modifyUser.getAddress());
			// userInDB.setAlipay(modifyUser.getAlipay());
			if (modifyUser.getBirthday() != null) {
				userInDB.setBirthday(modifyUser.getBirthday());
			} else {
				return new ResponseResult(0, "生日不能为空", null);
			}
			if (modifyUser.getImage() != null) {
				userInDB.setImage(modifyUser.getImage());
			} else {
				return new ResponseResult(0, "头像不能为空", null);
			}

			int sexCode = Integer.parseInt(modifyUser.getSex());
			if (sexCode < 3 && sexCode > -1) {
				userInDB.setSex(modifyUser.getSex()); // 0保密。1男。2女
			} else {
				return new ResponseResult(0, "性别只能为 0保密、1男、2女", null);
			}
			if (modifyUser.getUsername() != null) {
				userInDB.setUsername(modifyUser.getUsername());
			} else {
				return new ResponseResult(0, "昵称不能为空", null);
			}

			// userInDB.setIncome(modifyUser.getIncome());
			// userInDB.setJob(modifyUser.getJob());
			// userInDB.setMoneyPassword(modifyUser.getMoneyPassword());
			userService.update(userInDB);
			return new ResponseResult(1, "更新成功", userInDB);
		} catch (Exception e) {
			e.printStackTrace();
			return new ResponseResult(0, "更新失败", null);
		}
	}

	/**
	 * 更新个人头像。
	 * 
	 * @param user2
	 * @return
	 */
	@RequestMapping(value = "/modifyImage", method = RequestMethod.POST)
	@ResponseBody
	@RequiresAuthentication
	@RequiresRoles("customer")
	public ResponseResult modifyImage(User modifyUser) {
		try {
			User currentUser = (User) SecurityUtils.getSubject().getPrincipal();

			User userInDB = userService.getByPhone(currentUser.getPhone());

			if (modifyUser.getImage() != null) {
				userInDB.setImage(modifyUser.getImage());
			} else {
				return new ResponseResult(0, "头像不能为空", null);
			}
			userService.update(userInDB);
			return new ResponseResult(1, "更新成功", userInDB);
		} catch (Exception e) {
			e.printStackTrace();
			return new ResponseResult(0, "更新失败", null);
		}
	}

	/**
	 * 查看个人资料
	 * 
	 * @param user2
	 * @return
	 */
	@RequestMapping(value = "/look2")
	@ResponseBody
	@RequiresAuthentication
	@RequiresRoles("topBanner-administrator")
	public User look2() {
		// User user = UserUtils.getCurrentUser();
		// User dbuser = userService.getByAccount(user.getAccount());
		// if (null != dbuser) {
		// return dbuser;
		// }
		// u.setRoles(null);
		return null;
	}

	/**
	 * 查看Ta人资料
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/lookOther")
	@ResponseBody
	@RequiresAuthentication
	public User lookOther(@RequestParam(value = "phone", required = true) String phone) {

		User dbuser = userService.getByPhone(phone);
		if (null != dbuser) {
			return dbuser;
		}
		// u.setRoles(null);
		return null;
	}

	/**
	 * 查看Ta人资料
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/lookOtherById")
	@ResponseBody
	@RequiresAuthentication
	public User lookOtherById(@RequestParam(value = "id", required = true) long id) {

		User dbuser = userService.getById(User.class, id);
		if (null != dbuser) {
			return dbuser;
		}
		// u.setRoles(null);
		return null;
	}

	/**
	 * 测试权限 只有拥有 user:create 权限，才能进行注册
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/register")
	@ResponseBody
	@RequiresPermissions("user:create")
	public boolean register(User user) {
		return userService.register(user);
	}

	/**
	 * 测试角色 只有拥有 administrator 角色，才能跳转到register页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/toRegister")
	@RequiresRoles("administrator")
	public String toRegister() {
		Subject currentUser = SecurityUtils.getSubject();
		return "/system/user/register";
	}

	/**
	 * 清理授权缓存 还需要一个权限需要实现。。。就是管理员来clear clearCachedAuthorizationInfo
	 * 
	 * 假设管理员
	 * 
	 * @return
	 */
	@RequestMapping(value = "/clear")
	public String clear() {
		Subject currentUser = SecurityUtils.getSubject();

		RealmSecurityManager securityManager = (RealmSecurityManager) SecurityUtils.getSecurityManager();
		ShiroDbRealm sdr = (ShiroDbRealm) securityManager.getRealms().iterator().next();
		sdr.clearSomeoneCachedAuthorizationInfo("admin1111");
		// sdr.clearCachedAuthorizationInfo(currentUser.getPrincipal());
		// clearCachedAuthorizationInfo(currentUser.getPrincipals());
		return "/system/user/register";
	}
}
